<template>
  <div class="app-container">
    <!-- 日历视图 -->
    <el-card class="calendar-card">
      <div slot="header" class="clearfix">
        <span>用户考核日历</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="refreshMonth">刷新</el-button>
      </div>
      
      <!-- 日历组件：仅展示当月日期 -->
      <el-calendar v-model="currentDate" :range="monthRange">
        <template slot="dateCell" slot-scope="{date, data}">
          <div class="calendar-cell" @click="handleDateClick(data.day, data)">
            <template v-if="data.type === 'current-month'">
              <div class="date-number">{{ data.day.split('-').slice(2).join('') }}</div>
              <div class="score" v-if="dailyScoresMap[data.day] !== undefined">
                <el-tag :type="getScoreTagType(dailyScoresMap[data.day])" size="mini">考核总分：{{ dailyScoresMap[data.day] }}</el-tag>
              </div>
            </template>
            <template v-else>
              <div class="date-number other-month"></div>
            </template>
          </div>
        </template>
      </el-calendar>
    </el-card>




  </div>
</template>

<script>
import { getMonthDailyScores } from "@/api/system/assessScore"

export default {
  name: "AssessUser",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 用户考核表格数据（用于显示有无任务）
      assessUserList: [],

      // 当前日历日期
      currentDate: new Date(),

      // 每日总分映射 { 'yyyy-MM-dd': number }
      dailyScoresMap: {},

      // 查询参数（用于获取考核任务列表）
      queryParams: {
        pageNum: 1,
        pageSize: 1000,
        assessTaskId: null,
        userId: null,
        fraction: null,
        isFinish: null,
        taskDate: null,
        finalScore: null,
      }
    }
  },
  computed: {
    // 仅展示当前月份第一天到最后一天
    monthRange() {
      const y = this.currentDate.getFullYear()
      const m = this.currentDate.getMonth()
      const start = new Date(y, m, 1)
      const end = new Date(y, m + 1, 0)
      // 归零时间
      start.setHours(0, 0, 0, 0)
      end.setHours(23, 59, 59, 999)
      return [start, end]
    }
  },
  watch: {
    // 切换上月/下月/今天都会更新 v-model，从而触发此监听
    currentDate() {
      this.fetchMonthScores()
    }
  },
  created() {
    this.initMonthData()
  },
  activated() {
    this.initMonthData()
  },
  methods: {
    initMonthData() {
    
      this.fetchMonthScores()
    },
    refreshMonth() {
      this.initMonthData()
    },
    // 拉取当月每天总分
    fetchMonthScores() {
      const ym = this.formatYearMonth(this.currentDate)
      getMonthDailyScores(ym).then(res => {
        const list = res.data || res || []
        const map = {}
        list.forEach(row => {
          const day = this.normalizeDate(row.taskDate)
          map[day] = Number(row.score || 0)
        })
        this.dailyScoresMap = map
      }).catch(() => {
        this.dailyScoresMap = {}
      })
    },
    // 处理日期点击（忽略非当月日期）
    handleDateClick(date, data) {
      if (data && data.type !== 'current-month') return
      this.$router.push({
        path: '/system/assessUser/detail',
        query: { date }
      })
    },
    // 分数标签类型：<90 红色，否则绿色
    getScoreTagType(score) {
      const n = Number(score || 0)
      return n < 90 ? 'danger' : 'success'
    },
    // yyyy-MM
    formatYearMonth(d) {
      const y = d.getFullYear()
      const m = (d.getMonth() + 1).toString().padStart(2, '0')
      return `${y}-${m}`
    },
    // 规范化日期为 yyyy-MM-dd
    normalizeDate(val) {
      if (!val) return ''
      if (typeof val === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(val)) return val
      const d = new Date(val)
      const y = d.getFullYear()
      const m = (d.getMonth() + 1).toString().padStart(2, '0')
      const day = d.getDate().toString().padStart(2, '0')
      return `${y}-${m}-${day}`
    }
  }
}
</script>

<style scoped>
.calendar-card {
  margin-bottom: 20px;
}

.calendar-cell {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 4px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.calendar-cell:hover {
  background-color: #f5f7fa;
}

.date-number {
  font-size: 14px;
  font-weight: bold;
  color: #303133;
}

.other-month {
  visibility: hidden;
}

.task-badge {
  width: 100%;
}

.task-text {
  font-size: 10px;
  color: #409eff;
  background-color: #ecf5ff;
  padding: 2px 4px;
  border-radius: 2px;
}

.score {
  margin-top: 4px;
}
</style>
